#include "Ai_Message.h"

using namespace MessageSystem;

/************************************************************************/
/* DISPATCHER                                                           */
/************************************************************************/
void Message_Dispatcher::Update( float dt )
{
    m_timeStamp += dt;
    ProcessHandlers();
    if(m_messages.size() > 0 && m_handlers.size() > 0)
        ProcessMessages(dt);
    else
        m_timeStamp = 0.0f;
}
void Message_Dispatcher::RegisterHandler( Message_Handler* handler )
{
    m_handlers.push_back(handler);
}
void Message_Dispatcher::ProcessHandlers()
{
    //for each handler,
    for(unsigned int i = 0; i < m_handlers.size(); ++i)
    {
        //add all the msg's from its outbox
        Messages& outBox = m_handlers[i]->vGetOutBox();
        for(unsigned int msg = 0; msg < outBox.size(); ++msg)
        {
            outBox[msg].m_dispatchTime += m_timeStamp;
            m_messages.insert(outBox[msg]);
        }
        outBox.clear();
    }
}
void Message_Dispatcher::ProcessMessages( float dt )
{
    MessageSet::iterator msg = m_messages.begin();
    while(msg != m_messages.end() && msg->m_dispatchTime < m_timeStamp)
    {
        for(unsigned int i = 0; i < m_handlers.size(); ++i)
        {
            m_handlers[i]->vReceiveMessage(*msg);
        }
        m_messages.erase(msg);
        msg = m_messages.begin();
    }
    for(unsigned int i = 0; i < m_handlers.size(); ++i)
        m_handlers[i]->vProcessInbox();
}

void Message_Dispatcher::UnregisterAll()
{
    m_handlers.clear();
}

void Message_Dispatcher::ForceMessage( Ai_Message msg )
{
    m_messages.insert(msg);
}
